package com.tanquandan.askbackend.filter;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.tanquandan.askbackend.dto.R;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter
public class LoginFilter implements Filter {

    private final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    private final String[] whiteList = new String[]{
            "/employee/login",
            "/employee/logout",
            "/user/login",
            "/backend/login.html",
            "/backend/{[css,fonts,images,js,lib.layui]+}/**",
            "/frontend/login.html",
    };

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        HttpSession session = request.getSession();
        String requestURI = request.getRequestURI();

        // 1. 如果请求在白名单范围内，则放行
        if(filterURI(requestURI)){
            filterChain.doFilter(request,response);
            return;
        }

        // 2. 拦截后台用户登录：检查登录状态，如果登录，则放行
        Long employeeId = (Long)session.getAttribute("employee");
        if(!ObjectUtil.isEmpty(employeeId)){
            filterChain.doFilter(request,response);
            return;
        }

        // 3. 拦截前台用户登录：检查登录状态，如果登录，则放行
        Long userId = (Long)session.getAttribute("user");
        if(!ObjectUtil.isEmpty(userId)){
            filterChain.doFilter(request,response);
            return;
        }

        // 4. 返回错误
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 筛选请求地址是否在白名单内
     * @param requestURI
     * @return
     */
    private boolean filterURI(String requestURI){
        for (String uri : whiteList) {
            // 在白名单内
            if(PATH_MATCHER.match(uri,requestURI)) return true;
        }
        // 不在白名单内
        return false;
    }

}
